import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:xvideos/hj_page/home_business/home_cell_style/video_simple_cell_widget.dart';
import 'package:xvideos/hj_page/home_business/home_sub_module/widget/sort_header.dart';
import 'package:xvideos/hj_page/home_business/home_sub_module/widget/special_topics_view.dart';
import 'package:xvideos/routers/jump_router.dart';
import 'package:xvideos/tools_base/loading/loading_center_widget.dart';

import '../../../hj_model/cartoon_media_info.dart';
import '../../../hj_model/home/home_tabs_entity.dart';
import '../../../hj_model/video_model.dart';
import '../../../hj_utils/sliver_delegate.dart';
import '../../../tools_base/banner/ads_grid_view_widget.dart';
import '../../../tools_base/loading/l_error_widget.dart';
import '../../../tools_base/refresh/pull_refresh.dart';
import '../../cartoon_business/acg_widget_item.dart';
import '../home_cell_style/home_jg_area_widget.dart';
import 'home_tab_sort_logic.dart';

/// 海角样式
class HomeTabSortPage extends StatelessWidget {
  final ModuleData tabModel;
  final bool isDarkStyle;
  final int index;

  const HomeTabSortPage(
    this.index,
    this.tabModel, {
    Key? key,
    this.isDarkStyle = false,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GetBuilder<HomeTabSortLogic>(
      init: HomeTabSortLogic(index, tabModel, isDarkStyle: isDarkStyle),
      tag: "${tabModel.id}-${DateTime.now().millisecondsSinceEpoch}",
      builder: (logic) {
        return Stack(
          children: [
            Container(
              child: pullYsRefresh(
                onInit: (ctr) => logic.refreshController = ctr,
                onLoading: (ctr) => logic.loadMoreData(),
                onRefresh: (ctr) => logic.refreshData(),
                child: CustomScrollView(
                  controller: logic.scrollController,
                  slivers: [
                    if (!logic.isNewestStyle) ...[
                      SliverToBoxAdapter(
                        child: AdsGridViewWidget(
                          4,
                          isBigStyle: true,
                          padding: EdgeInsets.fromLTRB(12, 0, 12, 12),
                        ),
                      ),
                      SliverToBoxAdapter(child: HomeJgAreaWidget(tabModel)),
                      SliverToBoxAdapter(
                        child: SpecialTopicsView(
                          logic.allSection,
                          moudle: tabModel,
                          padding: EdgeInsets.fromLTRB(12, 0, 12, 12),
                          isDarkStyle: isDarkStyle,
                          isACG: tabModel.isACG,
                        ),
                      ),
                      SliverPersistentHeader(
                        pinned: true,
                        delegate: MySliverDelegate(
                          maxHeight: 42,
                          minHeight: 42,
                          callTop: (shrinkOffset) {
                            if (shrinkOffset > 0) {
                              WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
                                logic.isSortMenuInTop.value = false;
                              });
                            }
                            if (shrinkOffset <= 0) {
                              WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
                                logic.isSortMenuInTop.value = true;
                              });
                            }
                          },
                          child: Container(
                            child: Obx(
                              () {
                                Color? bgColor;
                                if (isDarkStyle) {
                                  if (logic.isSortMenuInTop.value) {
                                    bgColor = Colors.transparent;
                                  } else {
                                    bgColor = Colors.black;
                                  }
                                }
                                return HomeSortHeader(
                                  labelPadding: EdgeInsets.symmetric(horizontal: 10),
                                  tabs: logic.sortTitles,
                                  isInTop: logic.isSortMenuInTop.value == false,
                                  bgColor: bgColor,
                                  sortCallBack: (sort) {
                                    logic.sortMenuEvent(sort);
                                  },
                                  rightWidget: _buildSortStyleMenu(logic),
                                );
                              },
                            ),
                          ),
                        ),
                      ),
                    ],
                    _buildContent(logic),
                  ],
                ),
              ),
            ),
          ],
        );
      },
    );
  }

  Widget _buildSortStyleMenu(HomeTabSortLogic logic) {
    if (tabModel.isACG) return SizedBox();
    return Container(
      padding: EdgeInsets.only(right: 12),
      child: InkWell(
        onTap: logic.onTooleAction,
        child: Row(
          children: [
            Text(
              '切换',
              style: TextStyle(
                fontSize: 12,
                color: Colors.white.withOpacity(.6),
              ),
            ),
            SizedBox(width: 2),
            AnimatedSwitcher(
              duration: Duration(milliseconds: 300),
              transitionBuilder: (child, anim) {
                return ScaleTransition(child: child, scale: anim);
              },
              child: Image.asset(
                logic.isGridStyle.value ? 'assets/images/home/list_style.webp' : 'assets/images/home/grid_style.webp',
                key: ValueKey(logic.isGridStyle.value),
                width: 18,
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildContent(HomeTabSortLogic logic) {
    if (logic.isLoadingData) {
      return SliverFillRemaining(
        child: LoadingCenterWidget(),
      );
    } else if (logic.allVideo.isEmpty && logic.allMedia.isEmpty) {
      return SliverFillRemaining(
        child: CErrorWidget(
          retryOnTap: () => logic.initData(),
        ),
      );
    } else {
      if (tabModel.isACG) {
        return SliverPadding(
          padding: EdgeInsets.fromLTRB(16, 10, 16, 0),
          sliver: SliverGrid(
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 3,
              mainAxisSpacing: 12,
              crossAxisSpacing: 5,
              childAspectRatio: 111 / 194, //子控件宽高比
            ),
            delegate: SliverChildBuilderDelegate(
              (context, index) {
                CartoonMediaInfo info = logic.allMedia[index];
                return AcgItemWidget(info: info);
              },
              childCount: logic.allMedia.length,
            ),
          ),
        );
      } else {
        return SliverPadding(
          padding: EdgeInsets.fromLTRB(16, 10, 16, 0),
          sliver: SliverGrid(
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: logic.isGridStyle.value ? 2 : 1,
              mainAxisSpacing: logic.isGridStyle.value ? 12 : 14,
              crossAxisSpacing: 7,
              childAspectRatio: logic.isGridStyle.value ? 168 / 154 : 340 / 232, //子控件宽高比
            ),
            delegate: SliverChildBuilderDelegate(
              (context, index) {
                VideoModel videoModel = logic.allVideo[index];
                return GestureDetector(
                  onTap: () async {
                    pushToVideoPage(videoModel: videoModel);
                  },
                  child: VideoSimpleCellWidget(videoModel: videoModel),
                );
              },
              childCount: logic.allVideo.length,
            ),
          ),
        );
      }
    }
  }
}
